<template>
  <BaseTable
    class="table-style mt-2"
    bordered
    max-fill
    :loading="loading"
    :extra-height="64"
    column-code="001015"
    :scroll="{ x: 1000 }"
    :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
    :expanded-row-keys="expandedRowKeys"
    :exclude-columns="['status', 'orderType']"
    :data-source="dataSource"
  >
    <template #bodyCell="{ column, index, record }">
      <template v-if="column.dataIndex === 'xh'">
        {{ index + 1 }}
      </template>
      <template v-if="column.dataIndex === 'mc'">
        <EditCell title="项目">
          <SelectMedicine
            :value="record"
            type="补记账"
            :search-params="{
              xmlbbh: ['1']
            }"
            @select="(data) => onSelectTable(data, record)"
          />
          <!-- <SelectTable v-model:value="record.adviceName" type="补记账" :search-params="{ xmlbbh: ['1'] }" @select="(data) => onSelectTable(data, record)" /> -->
        </EditCell>
      </template>
      <template v-else-if="column.dataIndex === 'action'">
        <BaseButton confirm-text="作废项目?" size="small" danger type="text" @click="onDelete(record)"> 作废 </BaseButton>
      </template>
    </template>
    <template #footer>
      <div class="text-center sticky bottom-0">
        <a-button type="primary" class="mr-2" ghost :icon="h(PlusOutlined)" :disabled="!suitStore.currentSuit.id" @click="addRow()"> 新增一行 </a-button>
        <a-button type="primary" :icon="h(SaveOutlined)" :disabled="!isHaveNewRow()" @click="saveNewRows()"> 保存 </a-button>
      </div>
    </template>
  </BaseTable>
</template>
<script setup>
import { ref, h, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SaveOutlined } from '@ant-design/icons-vue'
import { post } from '@/utils/request'
import useSuitStore from '../store'

const loading = ref(false)
const suitStore = useSuitStore()
const expandedRowKeys = ref([])
const dataSource = ref([])
const generateRow = () => {
  return {
    id: '',
    key: `row-key-${Math.random().toString().slice(2)}`,
    isNew: true
  }
}
const isHaveNewRow = () => {
  return dataSource.value?.some((item) => item.isNew)
}

const saveNewRows = async () => {
  const newRows = dataSource.value.filter((item) => item.isNew)
  newRows.forEach((item) => {
    item.setId = suitStore.currentSuit.id
  })
  fetchSave(newRows)
}

const editRow = (row) => !row.isNew && fetchSave([row])
const fetchSave = async (rows) => {
  const { code, msg } = await post('/lis/LisPackage/doSaveLisAdviceSetDtList', [...rows])
  if (code !== 0) return message.error(msg || '操作失败')
  message.destroy()
  message.success('操作成功')
  await getData()
  // if (row.adviceCode) {
  // } else {
  //   message.destroy()
  //   message.error('请填写完整信息')
  // }
}

//获取数据
const getData = async () => {
  loading.value = true
  const { data, code } = await post('/lis/LisPackage/getLisAdviceSetDtList', { setId: suitStore.currentSuit.id })
  loading.value = false
  if (code !== 0) message.error('获取数据失败')
  if (data.length > 0) {
    expandedRowKeys.value = data.map((item) => 'row-key-' + item.id)
    dataSource.value = data
  } else {
    expandedRowKeys.value = []
    dataSource.value = []
  }
}
watch(
  () => suitStore.currentSuit.id,
  (val) => {
    val ? getData() : (dataSource.value = [])
  },
  {
    deep: true
  }
)
//选药
const onSelectTable = (medicine, row) => {
  row.adviceCode = medicine?.bh
  row.mc = medicine?.mc
  editRow(row)
}

const onDelete = async (row) => {
  if (row.isNew) {
    const index = dataSource.value.findIndex((item) => item.key === row.key)
    dataSource.value.splice(index, 1)
  } else {
    fetchDelete(row)
  }
}

const fetchDelete = async (row) => {
  const { code, msg } = await post('/lis/LisPackage/doDelLisAdviceSetDt', {
    id: row.id
  })
  if (code !== 0) return message.error(msg || '删除失败')
  message.success('删除成功')
  getData()
}

//添加行
const addRow = () => {
  const newRow = generateRow()
  expandedRowKeys.value.push(newRow.key)
  dataSource.value.push(newRow)
}
const partData = ref([])
// 获取部位
const getPositionList = async () => {
  const { code, data } = await post('/operation/opex/getDictPartList', {
    zjm: '',
    pageNum: 1,
    pageSize: 999
  })
  if (code !== 0) return
  partData.value = data.map((item) => {
    return {
      value: item.id,
      label: item.partName
    }
  })
}
onMounted(() => {
  getPositionList()
})
</script>
<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
